<template>
	<view class="box">
		<web-view class="web-view" :style="style" ref="webView" :webview-styles="webviewStyles" :src="webviewUrl"
			@message="webMessage" @onPostMessage="onWebMessage" :update-title="true"></web-view>
	</view>
</template>
<script>
	/**
	 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
	 */
	var wv;
	import baseConfig from '@/common/config'
	export default {
		data() {
			return {
				option: {},
				webviewUrl: '',
				webviewStyles: {
					progress: {
						color: '#FF7200'
					}
				},
				style: {
					flex: 1
				},
				toolbars: [{
						icon: 'icon-recordings',
						text: '录音',
						package: 'com.huawei.soundrecorder'
					},
					{
						icon: 'icon-camera',
						text: '全程录频',
						package: 'com.kimcy929.secretvideorecorder',
						downloadUrl: 'https://cxdy-enforce.oss-cn-hangzhou.aliyuncs.com/softwares/cxdy_hd_video.apk'
					},
					{
						icon: 'icon-draft',
						text: '绘制草图',
						package: 'com.newskyer.draw',
						downloadUrl: 'https://cxdy-enforce.oss-cn-hangzhou.aliyuncs.com/softwares/cxdy_hd_sketch_xiangzuo.apk'
					},
					{
						icon: 'icon-special-maps',
						text: '绘制专业图',
						package: 'com.sensopia.magicplan',
						downloadUrl: 'https://cxdy-enforce.oss-cn-hangzhou.aliyuncs.com/softwares/cxdy_hd_sketch_magicplan.apk'
					},
					{
						icon: 'icon-imou',
						text: '布控球控制',
						package: 'com.mm.android.lc',
						downloadUrl: 'https://cxdy-enforce.oss-cn-hangzhou.aliyuncs.com/softwares/cxdy_hd_sketch_lecheng.apk'
					}
				]
			};
		},
		onLoad(option) {
			console.log('vue page');
			// const res = uni.getSystemInfoSync();

			if (option.title != '') {
				uni.setNavigationBarTitle({
					title: option.title
				});
			}

			var height = 0; //定义动态的高度变量，如高度为定值，可以直接写
			uni.getSystemInfo({
				//成功获取的回调函数，返回值为系统信息
				success: (sysinfo) => {
					console.log('sysinfo:', sysinfo);
					height = sysinfo.windowHeight; //自行修改，自己需要的高度 此处如底部有其他内容，可以直接---(-50)这种
					// this.style = {
					// 	top: sysinfo.statusBarHeight + 'px',
					// 	width: sysinfo.screenWidth + 'px',
					// 	height: sysinfo.screenHeight + 'px'
					// };
					this.style = {
						width: sysinfo.screenWidth + 'px',
						height: (sysinfo.screenHeight - 44 - sysinfo.statusBarHeight) + 'px',
					}
					this.webviewUrl = decodeURIComponent(option.url);
				},
				complete: () => {}
			});

			// #ifdef APP-PLUS
			var currentWebview = this.$scope.$getAppWebview(); //获取当前web-view
			setTimeout(() => {
				wv = currentWebview.children()[0];
				wv.evalJS(`alert("uniApp 发送过来的数据")`)
				console.log('123');

				// wv.setStyle({ //设置web-view距离顶部的距离以及自己的高度，单位为px	
				// 	width: '300px',
				// 	top: 200 + 'px', //此处是距离顶部的高度，应该是你页面的头部
				// 	height: 20 + 'px', //webview的高度
				// 	scalable: false, //webview的页面是否可以缩放，双指放大缩小,
				// })
			}, 1); //如页面初始化调用需要写延迟
			// #endif
		},
		methods: {
			onWebMessage(e) {
				console.log(e);
			},
			webMessage(e) {
				console.log(e);
				let data = e.detail.data[0]
				let action = data.action
				if (action == 'success') {
					this.backPage()
					uni.showToast({
						title: '操作成功'
					});
				} else if (action == 'cancel') {
					this.backPage()
				} else if (action == 'openApp') {
					this.openApp(data.name)
				} else if (action == 'openDoc') {
					this.openDoc(data.url)
				} else if (action == 'previewImage') {
					this.previewImage(data.imgList)
				} else if (action == 'base64') {
					this.openUrl(data.url)
				} else if (action == 'submit') {
					this.submitForm(data.data)
				}
			},
			backPage() {
				uni.$emit('H5Back');
				uni.navigateBack({
					delta: 1
				});
			},
			openApp(pname) {
				// #ifdef APP-PLUS
				const isApp = plus.runtime.isApplicationExist({
					pname
				});

				if (isApp) {
					const sendData = {
						email: 'chenlengsu_it@163.com',
						password: 'password',
						mode: 'password'
					};
					plus.runtime.launchApplication({
							// pname: "com.sensopia.magicplan",
							// pname: "com.jideos.jnotes",
							pname,
							extra: sendData
						},
						e => {
							console.log('error', e.message);
						}
					);
				} else {
					console.log('App未安装~');
					let packageName = this.toolbars.filter(item => {
						return item.package == pname;
					});
					// this.isAppModule.downloadUrl = packageName[0].downloadUrl
					let that = this;
					uni.showModal({
						title: '提示',
						content: '检测到应用未安装，是否自动为您安装应用',
						cancelText: '取消',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								that.confirm(packageName[0].downloadUrl);
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
				// #endif
			},
			openDoc(url) {
				uni.downloadFile({
					url,
					success: function(res) {
						var filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function(res) {
								console.log('打开文档成功');
							}
						});
					}
				});
			},
			previewImage(imgList) {
				uni.previewImage({
					current: 0,
					urls: imgList,
					indicator: 'default',
					longPressActions: {
						itemList: [],
						success: function(data) {
							console.log(data);
						},
						fail: function(err) {}
					}
				});
			},
			openUrl(url) {
				plus.runtime.openURL(this.$store.state.vuex_config.H5baseUrl + url +
					'&pdfDownload=true')
			},
			confirm(url) {
				const downloadApkUrl = url;
				this._dtask = plus.downloader.createDownload(downloadApkUrl, {}, function(d, status) {
					// 下载完成
					if (status == 200) {
						console.log(plus.io.convertLocalFileSystemURL(d.filename));
						plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function(
							error) {
							uni.showToast({
								title: '安装失败',
								duration: 1500
							});
						});
					} else {
						uni.showToast({
							title: '更新失败',
							duration: 1500
						});
					}
				});
				try {
					this._dtask.start(); // 开启下载的任务
					this._prg = 0;
					// this._showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象

					uni.showLoading({
						title: '更新中……'
					});
					this._dtask.addEventListener('statechanged', this.stateChanged, false);
				} catch (err) {
					console.log('错误信息', err);
					plus.nativeUI.closeWaiting();
				}
			},
			submitForm(data) {
				uni.request({
					url: `${baseConfig.baseUrl}/archives/notice`,
					method: 'PUT',
					header: {
						'content-type': 'application/json',
						'Authorization': this.$store.state.vuex_token
					},
					data
				}).then(res => {
					if (res[1].data.code == 200) {
						this.backPage()
						uni.showToast({
							title: '操作成功'
						});
					}
				})
			},
			stateChanged(task, status) {
				// console.log(task.state);
				// console.log(this.prg);.
				// 给下载任务设置一个监听 并根据状态  做操作
				// console.log(this.downloadModel.content);
				switch (task.state) {
					case 1:
						// this._showLoading.setTitle("正在下载");
						// this.downloadModel.content = '正在下载'
						break;
					case 2:
						// this._showLoading.setTitle("已连接到服务器");
						// this.downloadModel.content = '已连接到服务器'
						break;
					case 3:
						this._prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) * 100);
						// this._showLoading.setTitle("  正在下载" + this._prg + "%  ");
						// this.downloadModel.content = "正在下载" + this._prg + "% "
						// uni.showLoading({
						// 	title: "正在下载" + this._prg + "% "
						// })
						break;
					case 4:
						plus.nativeUI.closeWaiting();
						// this.downloadModel.show = false
						//下载完成
						break;
				}
			},
			downloadModelCancel() {
				plus.downloader.clear();
			}
		}
	};
</script>
<style lang="scss">
	.web-view {
		// width: 100vw;
		// height: 100vh;

	}

	.slot-content {
		text-align: center;
	}

	.slot-content-view {
		padding: 40upx 0;
	}
</style>
